package com.media.appmedia.thread;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;

import com.android.volley.Response.Listener;
import com.android.volley.toolbox.ImageRequest;
import com.media.appmedia.util.FileUtils;
import com.media.appmedia.util.VolleyHepler;

public class SaveImageThread extends Thread {
	private ArrayList<String> imageUrls;
	private String filePath;
	private IsOk isOk;
	private int count;
	private static final CompressFormat format = CompressFormat.PNG;
	public SaveImageThread(ArrayList<String> imageUrls,IsOk isOk) {
		this.imageUrls = imageUrls;
		this.isOk = isOk;
		count = 0;
	}
	@Override
	public void run() {
			for(int i=0;i<imageUrls.size();i++){
				if(!FileUtils.isExist(imageUrls.get(i))){
					loadData(imageUrls.get(i));
				}else{
					if(count == imageUrls.size()-1){
						isOk.canGetOut();
					}
					count ++;
				}
			}
	}

	/**
	 * 
	 * 方法说明： 本地缓存图片封装方法
	 * 
	 * @param bitmap
	 * @param filePath
	 * @param format
	 * @throws IOException
	 */
	public synchronized void saveBitmap(Bitmap bitmap, String filePath)
			throws IOException {
		String str = FileUtils.createImgLoad();
		File files = new File(str);
		File file = new File(files, filePath.hashCode()+".png");
		files.mkdirs();
		OutputStream output = new FileOutputStream(file);
		bitmap.compress(format, 100, output);
		output.flush();
		output.close();
		
		if(count == imageUrls.size()-1){
			isOk.canGetOut();
		}
		count++;
	}

	private void loadData(final String url) {

		ImageRequest requests = new ImageRequest(url, new Listener<Bitmap>() {

			@Override
			public void onResponse(Bitmap response) {

				try {
					saveBitmap(response, url);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}, 0, 0, Config.ARGB_8888, null);
		requests.setTag(this);
		VolleyHepler.getInstance().addRequest(requests);
	}
	
	public interface IsOk{
		void canGetOut();
	}
}
